import defaultAxios, { AxiosResponse } from "axios";
import { errorNotify, getToken } from "@/utils/common";
import store from "@/store/store";
const tokenStr = getToken();
const axios = defaultAxios.create({
  baseURL: "/api", // 接口url统一前缀
  timeout: 10000, // 设置超时
  headers: {
    "Content-Type": "application/json;charset=UTF-8;",
    token: tokenStr,
  },
});

axios.interceptors.request.use(
  (req) => {
    // 如果是get请求，并且有params参数，将自动拼接url路径参数
    if (req.method === "get" && req.params) {
      let url = req.url + "?";
      for (const propName of Object.keys(req.params)) {
        const value = req.params[propName];
        let part = encodeURIComponent(propName) + "=";
        if (value !== null && typeof value !== "undefined") {
          if (typeof value === "object") {
            for (const key of Object.keys(value)) {
              let params = propName + "[" + key + "]";
              let subPart = encodeURIComponent(params) + "=";
              url += subPart + encodeURIComponent(value[key]) + "&";
            }
          } else {
            url += part + encodeURIComponent(value) + "&";
          }
        }
      }
      url = url.slice(0, -1);
      req.params = {};
      req.url = url;
    }
    return req;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (res): AxiosResponse => {
    // 统一处理错误信息
    if (res.data.code === 1) {
      errorNotify(res.data.message);
    } else if (res.data.code === 2) {
      store().setLoginBox(true);
    }
    return res;
  },
  (error) => {
    let message = "未知错误";
    console.log(error);
    //响应错误
    if (error.response && error.response.status) {
      const status = error.response.status;
      switch (status) {
        case 400:
          message = "请求错误";
          break;
        case 401:
          message = "请求错误";
          break;
        case 404:
          message = "请求地址出错";
          break;
        case 408:
          message = "请求超时";
          break;
        case 500:
          message = "服务器内部错误!";
          break;
        case 501:
          message = "服务未实现!";
          break;
        case 502:
          message = "网关错误!";
          break;
        case 503:
          message = "服务不可用!";
          break;
        case 504:
          message = "网关超时!";
          break;
        case 505:
          message = "HTTP版本不受支持";
          break;
        default:
          message = "请求失败";
      }
    }
    errorNotify(message);
    return Promise.reject(error.response);
  }
);

export default axios;
